<?php

/**
 * 自动更新钩子
 */

// 接收的信息
$json = $GLOBALS['HTTP_RAW_POST_DATA'];
$data = json_decode($json, true);

if ($data['state'] == 'merged' && $data['merge_status'] == 'can_be_merged') {

	//打开网站目录下的hooks.log文件 需要在服务器上创建 并给写权限
    $fs = fopen('./../webhook/sfmtp.log', 'a');

    fwrite($fs, '================ Update Start ===============' . PHP_EOL . PHP_EOL);

	//自定义字串掩码 用于验证
    $access_token = 'ee6e1d76262fcefa43a05f';

    $client_token = $data['password'];

	// 请求ip
    $client_ip = $_SERVER['REMOTE_ADDR'];

	//把请求的IP和时间写进log
    fwrite($fs, 'Request on [' . date("Y-m-d H:i:s") . '] from [' . $client_ip . ']' . PHP_EOL);

	//验证token 有错就写进日志并退出
    if ($client_token !== $access_token) {
        echo "error 403";
        fwrite($fs, "Invalid token [{$client_token}]" . PHP_EOL);
        $fs and fclose($fs);
        exit(0);
    }

	//如果有需要 可以打开下面，把传送过来的信息写进log
    fwrite($fs, 'Data: ' . print_r($data, true) . PHP_EOL);

	//执行shell命令并把返回信息写进日志
    exec('sudo -u www git pull origin master 2<&1', $output);
    fwrite($fs, 'Info:' . print_r($output, true) . PHP_EOL);

    fwrite($fs, PHP_EOL . '================ Update End ===============' . PHP_EOL . PHP_EOL);

    $fs and fclose($fs);

    echo json_encode($output);
}
